/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */


var EXPORTED_SYMBOLS =
[
    "CachingDataSource",
    "DecoratingDataSource",
    "MemoryDataSource",
    "PreferenceDataSource",
    "TransformingDataSource"
];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

Cu.import("resource://savefileto/common.jsm");


function PreferenceDataSource(prefName)
// extends ListenerManager
// implements nsIObserver
{
    ListenerManager.call(this);
    
    this.pref = Services.prefs.getBranch(prefName);
    this.pref.addObserver("", this, true);
    
    this.listeners = [];
}

PreferenceDataSource.prototype =
{
    QueryInterface: XPCOMUtils.generateQI([
        Ci.nsIObserver,
        Ci.nsISupports,
        Ci.nsISupportsWeakReference]),
    
    get entries()
    {
        try
        {
            var json = this.pref.getComplexValue("", Ci.nsISupportsString).data;
            var entries = JSON.parse(json);
            return entries;
        }
        catch (e)
        {
            Cu.reportError(e);
            return [];
        }
    },
    
    set entries(entries)
    {
        if (! Array.isArray(entries))
            throw new Error("not an array: " + entries);
        
        var json = JSON.stringify(entries);
        var str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
        str.data = json;
        this.pref.setComplexValue("", Ci.nsISupportsString, str);
    },
    
    // nsIObserver
    observe: function PrefDS_observe(subject, topic, data)
    {
        this.notifyListeners(this);
    }
}

extend(PreferenceDataSource, ListenerManager);


function MemoryDataSource(entries)
// extends ListenerManager
{
    ListenerManager.call(this);
    
    this.entries = entries;
}

MemoryDataSource.prototype =
{
    get entries()
    {
        return this._entries;
    },
    
    set entries(entries)
    {
        if (! Array.isArray(entries))
            throw new Error("not an array: " + entries);
        
        this._entries = entries.slice();
        this.notifyListeners(this);
    },
}

extend(MemoryDataSource, ListenerManager);


function DecoratingDataSource(dataSource)
{
    this.dataSource = dataSource;
}

DecoratingDataSource.prototype =
{
    get entries()
    {
        return this.dataSource.entries;
    },
    
    set entries(entries)
    {
        this.dataSource.entries = entries;
    },
    
    addListener: function DecoDS_addListener(callback)
    {
        return this.dataSource.addListener(callback);
    },
    
    removeListener: function DecoDS_removeListener(callback)
    {
        this.dataSource.removeListener(callback);
    },
    
    notifyListeners: function DecoDS_notifyListeners(/* args... */)
    {
        this.dataSource.notifyListeners.apply(this.dataSource, arguments);
    },
}


function TransformingDataSource(dataSource, getTransformer, setTransformer)
// extends DecoratingDataSource
{
    DecoratingDataSource.call(this, dataSource);
    
    this.getTransformer = getTransformer;
    this.setTransformer = setTransformer;
}

TransformingDataSource.prototype =
{
    get entries()
    {
        var entries = this.dataSource.entries;
        entries = this._transform(this.getTransformer, entries);
        return entries;
    },
    
    set entries(value)
    {
        if (! Array.isArray(value))
            throw new Error("not an array: " + value);
        
        var entries = this._transform(this.setTransformer, value);
        this.dataSource.entries = entries;
    },
    
    _transform: function TransDS__transform(transformer, value)
    {
        return (transformer ? transformer.transform(value) : value);
    }
}

extend(TransformingDataSource, DecoratingDataSource);


function CachingDataSource(dataSource, writeThrough)
// extends DecoratingDataSource
{
    DecoratingDataSource.call(this, dataSource);
    
    this.writeThrough = writeThrough;
    
    var self = this;
    this.resetListener = dataSource.addListener(function() { self.reset(); });
}

CachingDataSource.prototype =
{
    get entries()
    {
        if (! this._entries)
            this._entries = this.dataSource.entries;
        
        return this._entries;
    },
    
    set entries(entries)
    {
        if (this.writeThrough)
        {
            this.dataSource.entries = entries;
            this.reset();
        }
        else
            this._entries = entries;
    },
    
    flush: function CacheDS_flush()
    {
        if ((! this.writeThrough) && this._entries)
            this.dataSource.entries = this._entries;
    },
    
    reset: function CacheDS_reset()
    {
        delete this._entries;
    }
}

extend(CachingDataSource, DecoratingDataSource);
